<template>
  <div class="workflow-designer">
    <el-page-header @back="goBack" title="返回" content="工作流设计器"></el-page-header>
    
    <el-form :model="workflowForm" label-width="100px" class="workflow-form">
      <el-form-item label="工作流名称" required>
        <el-input v-model="workflowForm.name" placeholder="请输入工作流名称"></el-input>
      </el-form-item>
      <el-form-item label="工作流描述">
        <el-input 
          type="textarea" 
          v-model="workflowForm.description" 
          placeholder="请输入工作流描述"
        ></el-input>
      </el-form-item>
    </el-form>

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>工作流流程设计</span>
        </div>
      </template>
      <div class="bpmn-container">
        <bpmn-editor
          ref="bpmnEditor"
          @bpmn-modified="onBpmnModified"
        ></bpmn-editor>
      </div>
    </el-card>

    <el-card class="box-card form-card">
      <template #header>
        <div class="card-header">
          <span>任务表单设计</span>
          <el-select 
            v-model="selectedTask" 
            placeholder="选择任务节点" 
            class="task-select"
            @change="onTaskChange"
          >
            <el-option
              v-for="task in userTasks"
              :key="task.id"
              :label="task.name || task.id"
              :value="task.id"
            ></el-option>
          </el-select>
        </div>
      </template>
      <div v-if="selectedTask" class="form-container">
        <form-editor
          ref="formEditor"
          :initial-schema="getCurrentTaskFormSchema()"
          :initial-ui-schema="getCurrentTaskUiSchema()"
          @save="saveTaskForm"
          @error="handleFormError"
        ></form-editor>
      </div>
      <div v-else class="no-task-selected">
        <el-empty description="请先选择一个用户任务节点"></el-empty>
      </div>
    </el-card>

    <div class="button-container">
      <el-button type="primary" @click="saveWorkflow">保存工作流</el-button>
      <el-button @click="goBack">取消</el-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import BpmnEditor from '@/components/BpmnEditor.vue';
import FormEditor from '@/components/FormEditor.vue';
import { parseString } from 'xml2js';

export default {
  name: 'WorkflowDesigner',
  components: {
    BpmnEditor,
    FormEditor
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const bpmnEditor = ref(null);
    const formEditor = ref(null);
    
    const workflowForm = reactive({
      id: null,
      name: '',
      description: '',
      bpmnXml: '',
      taskForms: {}
    });
    
    const userTasks = ref([]);
    const selectedTask = ref('');
    const isNewWorkflow = ref(true);
    
    const goBack = () => {
      router.push('/workflow/list');
    };
    
    const extractUserTasks = (xml) => {
      parseString(xml, { explicitArray: false }, (err, result) => {
        if (err) {
          console.error('解析BPMN XML失败:', err);
          return;
        }
        
        try {
          const processes = result.definitions.process;
          const processArray = Array.isArray(processes) ? processes : [processes];
          
          const tasks = [];
          processArray.forEach(process => {
            if (process.userTask) {
              const userTaskArr = Array.isArray(process.userTask) 
                ? process.userTask 
                : [process.userTask];
              
              userTaskArr.forEach(task => {
                tasks.push({
                  id: task.$.id,
                  name: task.$.name || task.$.id
                });
              });
            }
          });
          
          userTasks.value = tasks;
          
          // 如果任务列表变了，并且当前选中的任务不在新的任务列表中，则重置选中的任务
          if (selectedTask.value && !tasks.some(task => task.id === selectedTask.value)) {
            selectedTask.value = '';
          } else if (tasks.length > 0 && !selectedTask.value) {
            selectedTask.value = tasks[0].id;
          }
        } catch (error) {
          console.error('提取用户任务失败:', error);
        }
      });
    };
    
    const onBpmnModified = (xml) => {
      workflowForm.bpmnXml = xml;
      extractUserTasks(xml);
    };
    
    const onTaskChange = (taskId) => {
      selectedTask.value = taskId;
    };
    
    const getCurrentTaskFormSchema = () => {
      if (!selectedTask.value || !workflowForm.taskForms[selectedTask.value]) {
        return null;
      }
      return workflowForm.taskForms[selectedTask.value].schema;
    };
    
    const getCurrentTaskUiSchema = () => {
      if (!selectedTask.value || !workflowForm.taskForms[selectedTask.value]) {
        return null;
      }
      return workflowForm.taskForms[selectedTask.value].uiSchema;
    };
    
    const saveTaskForm = (formDefinition) => {
      if (!selectedTask.value) return;
      
      workflowForm.taskForms[selectedTask.value] = formDefinition;
      ElMessage.success('表单已保存');
    };
    
    const handleFormError = (error) => {
      ElMessage.error(error);
    };
    
    const saveWorkflow = async () => {
      if (!workflowForm.name) {
        ElMessage.error('请输入工作流名称');
        return;
      }
      
      if (!workflowForm.bpmnXml) {
        ElMessage.error('请先设计工作流流程');
        return;
      }
      
      try {
        const workflow = {
          ...workflowForm
        };
        
        // 调用API保存工作流
        let response;
        if (isNewWorkflow.value) {
          // 创建新工作流
          response = await fetch('/api/workflows', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(workflow)
          });
        } else {
          // 更新已有工作流
          response = await fetch(`/api/workflows/${workflowForm.id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(workflow)
          });
        }
        
        if (!response.ok) {
          throw new Error('保存工作流失败');
        }
        
        ElMessage.success('工作流保存成功');
        router.push('/workflow/list');
      } catch (error) {
        ElMessage.error(error.message || '保存工作流失败');
      }
    };
    
    const loadWorkflow = async (id) => {
      try {
        const response = await fetch(`/api/workflows/${id}`);
        if (!response.ok) {
          throw new Error('获取工作流详情失败');
        }
        
        const data = await response.json();
        workflowForm.id = data.id;
        workflowForm.name = data.name;
        workflowForm.description = data.description;
        workflowForm.bpmnXml = data.bpmnXml;
        workflowForm.taskForms = data.taskForms || {};
        
        if (data.bpmnXml) {
          extractUserTasks(data.bpmnXml);
          if (bpmnEditor.value) {
            bpmnEditor.value.loadXml(data.bpmnXml);
          }
        }
      } catch (error) {
        ElMessage.error(error.message || '获取工作流详情失败');
      }
    };
    
    onMounted(() => {
      const id = route.params.id;
      if (id && id !== 'create') {
        isNewWorkflow.value = false;
        loadWorkflow(id);
      } else {
        workflowForm.taskForms = {};
      }
      
      // 监听BPMN编辑器初始化事件
      if (bpmnEditor.value) {
        bpmnEditor.value.$on('initialized', (xml) => {
          workflowForm.bpmnXml = xml;
          extractUserTasks(xml);
        });
      }
    });
    
    return {
      workflowForm,
      userTasks,
      selectedTask,
      bpmnEditor,
      formEditor,
      onBpmnModified,
      onTaskChange,
      goBack,
      saveWorkflow,
      saveTaskForm,
      handleFormError,
      getCurrentTaskFormSchema,
      getCurrentTaskUiSchema
    };
  }
};
</script>

<style scoped>
.workflow-designer {
  padding: 20px;
}

.workflow-form {
  margin: 20px 0;
}

.box-card {
  margin-bottom: 20px;
}

.form-card {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-select {
  width: 250px;
}

.bpmn-container {
  height: 500px;
  width: 100%;
}

.form-container {
  height: 600px;
  width: 100%;
}

.no-task-selected {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.button-container {
  margin-top: 20px;
  text-align: center;
}
</style> 